package net.thetabx.ftdba.activities;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import net.thetabx.ftdba.GlobalData;
import net.thetabx.ftdba.R;
import net.thetabx.ftdba.RStatus;
import net.thetabx.ftdba.http.HttpData;
import net.thetabx.ftdba.http.HttpManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class TorrentDetailsActivity extends Activity {
	private static final String TAG = "TorrentDetailsActivity";
	private HttpManager http;
	private Resources res;
	
	private TextView txtTitle;
	private TextView txtSeeders;
	private TextView txtLeechers;
	private TextView txtCompleted;
	private TextView txtSize;
	private TextView txtDate;
	private ImageView imgPic;
	
	private String autogetPageURL, torrentUrl, title;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.torrent_details);
        
        txtTitle = (TextView)findViewById(R.id.txtTorrentDetailsTitle);
        txtSeeders = (TextView)findViewById(R.id.txtTorrentDetailsSeeders);
        txtLeechers = (TextView)findViewById(R.id.txtTorrentDetailsLeechers);
        txtCompleted = (TextView)findViewById(R.id.txtTorrentDetailsCompleted);
        txtSize = (TextView)findViewById(R.id.txtTorrentDetailsSize);
        txtDate = (TextView)findViewById(R.id.txtTorrentDetailsDate);
        imgPic = (ImageView)findViewById(R.id.imgTorrentDetailsPic);
        res = getResources();
        http = GlobalData.getHttpManager();
        
        new TorrentDetailsPuller().execute((String) getIntent().getExtras().get("torrent_id"));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.torrent_details, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.menu_details_dl: {
        		//startActivity(new Intent(this, ShoutboxActivity.class));
            	new TorrentFileGetter().execute(torrentUrl, title);
        		return true;
            }
            case R.id.menu_details_autoget: {
            	new AutogetLinkGetter().execute(autogetPageURL);
        		return true;
            }
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    public void setText(final TextView view, final String str) {
    	view.post(new Runnable() {
            public void run() {
            	view.setText(str);
            }
        });
    }
    
    public class TorrentDetailsPuller extends AsyncTask<String, Boolean, RStatus> {
    	ProgressDialog torrentPullDialog;
		String debug, seeders, leechers, completed, size, date;
		Bitmap pic;
		
		@Override
		protected void onPreExecute() {
			torrentPullDialog = ProgressDialog.show(TorrentDetailsActivity.this, "", res.getString(R.string.torrent_details_pulling), true, false);
		}
		
		@Override
		protected RStatus doInBackground(String... params) {
			if(http == null)
				return RStatus.NO_HTTP;
			
			Log.v(TAG, "Pulling torrent details");
			HttpData data = http.send("/?section=INFOS&ajax=1&module=mod_infos&id=" + params[0]);
			if(data.getStatus() != RStatus.ENDED)
				return data.getStatus();
			
			// Parse data
			Document htmlDoc = Jsoup.parse(data.getContentSb().toString());
			
			title = htmlDoc.select(".torrents_infos_l h3").first().text();
			Elements images = htmlDoc.select(".torrents_infos_l img");
			
			pic = null;
			int i = 0;
			String imageUrl = null;
			try {
				while(true) {
					i++;
					Element image = images.get(i);
					if(image == null)
						break;
					
					imageUrl = image.attr("src").split("&")[0];
					if(imageUrl == null)
						break;
					
					pic = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
					if(pic == null || pic.getHeight() <= 140) {
						Log.v(TAG, "Can't get pic " + i + " or seems too small (" + imageUrl + "), trying next one");
						continue;
					}
					else
						break;
				}
			} catch (Exception e) {
				Log.d(TAG, "Can't build torrent pic : " + imageUrl);
				e.printStackTrace();
				return RStatus.ERROR;
			}
			
			Elements torrentStats = htmlDoc.select(".menu_box_stats div span");
			seeders = torrentStats.get(0).text();
			leechers = torrentStats.get(1).text();
			completed = torrentStats.get(2).text();
			size = torrentStats.get(3).text();
			date = torrentStats.get(4).text();
			
			torrentUrl = htmlDoc.select(".dl_link").first().attr("href");
			autogetPageURL = "/?section=INFOS&id=" + params[0] + "&menu=4&ajax=1&module=mod_infos";
			return RStatus.ENDED;
		}
		
		@Override
		protected void onPostExecute(final RStatus status) {
			torrentPullDialog.dismiss();
			if(status == RStatus.ENDED) {
				setText(txtTitle, title);
				setText(txtSeeders, seeders);
				setText(txtLeechers, leechers);
				setText(txtCompleted, completed);
				setText(txtSize, size);
				setText(txtDate, date);
				
				if(pic != null)
					imgPic.setImageBitmap(pic); 
        	}
        	else
        		Log.d(TAG, "Can't pull torrent details : " + status.name());
		}
	}
    
    public class AutogetLinkGetter extends AsyncTask<String, Boolean, RStatus> {
    	ProgressDialog autogetLinkDialog;
    	String autogetUrl;
		
		@Override
		protected void onPreExecute() {
			autogetLinkDialog = ProgressDialog.show(TorrentDetailsActivity.this, "", res.getString(R.string.torrent_details_autoget_pulling), true, false);
		}
		
		@Override
		protected RStatus doInBackground(String... params) {
			if(http == null)
				return RStatus.NO_HTTP;
			
			Log.v(TAG, "Getting autolink");
			HttpData data = http.send(params[0]);
			if(data.getStatus() != RStatus.ENDED)
				return data.getStatus();
			
			// Parse data
			Document htmlDoc = Jsoup.parse(data.getContentSb().toString());
			
			autogetUrl = htmlDoc.select(".autoget div a").first().attr("href");
			return RStatus.ENDED;
		}
		
		@Override
		protected void onPostExecute(final RStatus status) {
			autogetLinkDialog.dismiss();
			if(status == RStatus.ENDED) {
				ClipboardManager clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
				clipboard.setText(autogetUrl);
				Toast.makeText(getApplicationContext(), res.getString(R.string.torrent_details_autoget_pulled) + "\n" + autogetUrl, Toast.LENGTH_SHORT).show();
        	}
        	else
        		Log.d(TAG, "Can't get autolink : " + status.name());
		}
	}
    
    public class TorrentFileGetter extends AsyncTask<String, Integer, RStatus> {
    	ProgressDialog torrentDlDialog;
    	String torrentPath;
    	String debugMsg;
		
		@Override
		protected void onPreExecute() {
			torrentDlDialog = ProgressDialog.show(TorrentDetailsActivity.this, "", res.getString(R.string.torrent_details_dl_dling), true, false);
		}
		
		@Override
		protected RStatus doInBackground(String... params) {
			if(http == null)
				return RStatus.NO_HTTP;
			
			Log.v(TAG, "Downloading .torrent");
			try {
				torrentPath = Environment.getExternalStorageDirectory().getPath() + "/download/" + params[1] + ".torrent";

				InputStream input = new BufferedInputStream(http.download(params[0]));
	            OutputStream output = new FileOutputStream(torrentPath);
	            
	            byte data[] = new byte[1024];
	            int count;
	            while ((count = input.read(data)) != -1) {
	                output.write(data, 0, count);
	            }

	            output.flush();
	            output.close();
	            input.close();
			}
			catch(Exception e) {
				Log.d(TAG, "Can't get .torrent : " + params[1]);
				e.printStackTrace();
				return RStatus.ERROR;
			}
            
			return RStatus.ENDED;
		}
		
	    @Override
	    protected void onProgressUpdate(Integer... progress) {
	        super.onProgressUpdate(progress);
	        torrentDlDialog.setProgress(progress[0]);
	    }
		
		@Override
		protected void onPostExecute(final RStatus status) {
			torrentDlDialog.dismiss();
			if(status == RStatus.ENDED) {
				Toast.makeText(getApplicationContext(), res.getString(R.string.torrent_details_dl_dled) + "\n" + torrentPath, Toast.LENGTH_SHORT).show();
        	}
        	else
        		Log.d(TAG, "Can't download .torrent : " + status.name());
		}
	}
}
